﻿using EasyAbp.Abp.Aliyun.Common;
using EasyAbp.Abp.Aliyun.Common.Model;
using EasyAbp.Abp.Aliyun.Sms;
using EasyAbp.Abp.Aliyun.Sms.Model.Request;
using EasyAbp.Abp.Aliyun.Sms.Model.Response;
using EasyAbp.Abp.PhoneNumberLogin.Provider.Aliyun.Settings;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Volo.Abp.Json;
using Volo.Abp.Settings;
using Volo.Abp.Sms;

namespace EasyAbp.Abp.PhoneNumberLogin.Provider.Aliyun
{
    public class AliyunSmsSender : ISmsSender
    {
        private readonly IJsonSerializer _jsonSerializer;
        private readonly IAliyunApiRequester _requester;
        private readonly AbpAliyunSmsOptions _smsOptions;
        private readonly ILogger<AliyunSmsSender> _logger;
        private readonly ISettingProvider _settingProvider;
        public AliyunSmsSender(
            IJsonSerializer jsonSerializer,
            IAliyunApiRequester requester,
            IOptions<AbpAliyunSmsOptions> smsOptions,
            ILogger<AliyunSmsSender> logger,
            ISettingProvider settingProvider)
        {
            _jsonSerializer = jsonSerializer;
            _requester = requester;
            _smsOptions = smsOptions.Value;
            _logger = logger;

            _settingProvider = settingProvider;
        }
        public async Task SendAsync(SmsMessage smsMessage)
        {
            var request = new SendSmsRequest(smsMessage.PhoneNumber,
               GetStringProperty(smsMessage, PhoneNumberLoginProviderAliyunConsts.SignName),
              GetStringProperty(smsMessage, PhoneNumberLoginProviderAliyunConsts.TemplateCode),
              GetTemplateProperty(smsMessage, PhoneNumberLoginProviderAliyunConsts.TemplateParam));

            var res = await _requester.SendRequestAsync<SmsCommonResponse>(request,
                 await _settingProvider.GetOrNullAsync(PhoneNumberLoginProviderAliyunSettings.EndPoint) ?? _smsOptions.EndPoint);
            _logger.LogInformation($"[{res.Code}]{res.Message}");
        }

        protected virtual string GetStringProperty(SmsMessage smsMessage, string key, string defaultValue = null)
        {
            var str = smsMessage.Properties.GetOrDefault(key) as string;

            return !str.IsNullOrEmpty() ? str : defaultValue;
        }
        protected virtual string GetTemplateProperty(SmsMessage smsMessage, string key, string defaultValue = null)
        {
            var obj = smsMessage.Properties.GetOrDefault(key);

            if (obj != null)
            {
                return _jsonSerializer.Serialize(obj);
            }
            throw new Exception("未实现");
        }
    }
}
